package com.lgkj.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lgkj.R;
import com.lgkj.adapter.CarAdapter;
import com.lgkj.bean.meitao.CarGoodsBean;
import com.lgkj.bean.meitao.ComfirOrderBean;
import com.lgkj.ui.shop.ComfirOrderActivity;
import com.lgkj.utils.CommonConstant;
import com.lgkj.utils.CommonUtils;
import com.lgkj.utils.HttpUtils;
import com.lgkj.utils.SharedPreferencesUtils;

import org.json.JSONObject;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/8/20 0020.
 */

public class CarFragment extends Fragment {
    private static final String TAG = "CarFragment";
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.cb_all)
    CheckBox cbAll;
    @BindView(R.id.lv_car)
    ListView lvCar;
    private View view;
    private CarAdapter carAdapter;
    private CarGoodsBean bean;
    private List<ComfirOrderBean> comfirOrderBean;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.main_car_fragment, null);
        ButterKnife.bind(this, view);
        carAdapter = new CarAdapter(getActivity());
        comfirOrderBean = new ArrayList<>();
        lvCar.setAdapter(carAdapter);
        return view;
    }

    public static boolean isResu = true;

    @Override
    public void onResume() {
        if (isResu)
            init();
        super.onResume();
    }


    private void init() {
        getCar();
        carAdapter.setCallBack(new CarAdapter.CallBack() {
            @Override
            public void clickJian(int i) {
                CarGoodsBean.DataBean dataBean = carAdapter.getItem(i);
                int countNum = dataBean.getGoods_num();
                if (countNum > 1) {
                    countNum = countNum - 1;
                } else
                    Toast.makeText(getActivity(), "至少购买一个商品", Toast.LENGTH_SHORT).show();
                bean.getData().get(i).setGoods_num(countNum);
                carAdapter.notifyDataSetChanged();
                calculationTotal();
            }

            @Override
            public void clickAdd(int i) {
                CarGoodsBean.DataBean dataBean = carAdapter.getItem(i);
                int countNum = dataBean.getGoods_num();
                countNum = countNum + 1;
                bean.getData().get(i).setGoods_num(countNum);
                carAdapter.notifyDataSetChanged();
                calculationTotal();
            }

            @Override
            public void clickcb(int i) {
                calculationTotal();
            }
        });
    }

    private void calculationTotal() {
        comfirOrderBean.clear();
        BigDecimal totalPrice = BigDecimal.ZERO;
        Log.i(TAG, "calculationTotal: " + carAdapter.getCarGoodsBean().size());
        for (int i = 0; i < carAdapter.getCarGoodsBean().size(); i++) {
            if (carAdapter.getCarGoodsBean().get(i).isAdd()) {
                BigDecimal bDouble = new BigDecimal(carAdapter.getCarGoodsBean().get(i).getGoods_num());
                BigDecimal bString = new BigDecimal(carAdapter.getCarGoodsBean().get(i).getGoods_price());
                BigDecimal num = bDouble.multiply(bString);
                totalPrice = totalPrice.add(num);
                ComfirOrderBean beans = new ComfirOrderBean();
                beans.setGoods_num(carAdapter.getCarGoodsBean().get(i).getGoods_num());
                beans.setGoods_price(carAdapter.getCarGoodsBean().get(i).getGoods_price());
                beans.setGoods_price1(carAdapter.getCarGoodsBean().get(i).getGoods_price());
                beans.setGoods_name(carAdapter.getCarGoodsBean().get(i).getGoods_name());
                beans.setCover_id(carAdapter.getCarGoodsBean().get(i).getCover_id());
                beans.setGoods_model_id(carAdapter.getCarGoodsBean().get(i).getGoods_model_id());
                beans.setGoods_id(carAdapter.getCarGoodsBean().get(i).getGoods_id());
                beans.setId(carAdapter.getCarGoodsBean().get(i).getId());
                beans.setTotalPrice(totalPrice);
                comfirOrderBean.add(beans);
            }
        }
        Log.i(TAG, "calculationTotal: " + totalPrice);
        tvPrice.setText(totalPrice.setScale(2, RoundingMode.HALF_UP) + "");

    }

    private void calculationTotals() {
        comfirOrderBean.clear();
        BigDecimal totalPrices = BigDecimal.ZERO;
        for (int i = 0; i < bean.getData().size(); i++) {
            BigDecimal bDouble = new BigDecimal(bean.getData().get(i).getGoods_num());
            BigDecimal bString = new BigDecimal(bean.getData().get(i).getGoods_price());
            BigDecimal num = bDouble.multiply(bString);
            totalPrices = totalPrices.add(num);
            ComfirOrderBean beans = new ComfirOrderBean();
            beans.setGoods_num(bean.getData().get(i).getGoods_num());
            beans.setGoods_price(bean.getData().get(i).getGoods_price());
            beans.setGoods_name(bean.getData().get(i).getGoods_name());
            beans.setCover_id(bean.getData().get(i).getCover_id());
            beans.setGoods_model_id(bean.getData().get(i).getGoods_model_id());
            beans.setGoods_id(bean.getData().get(i).getGoods_id());
            beans.setId(bean.getData().get(i).getId());
            beans.setTotalPrice(totalPrices);
            comfirOrderBean.add(beans);
        }
        Log.i(TAG, "calculationTotal: " + totalPrices);
        tvPrice.setText(totalPrices.setScale(2, RoundingMode.HALF_UP) + "");

    }

    @OnClick({R.id.tv_right, R.id.cb_all, R.id.iv_car_total})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_right:
                delCar();
                break;
            case R.id.cb_all:
                if (cbAll.isChecked()) {
                    calculationTotals();
                    carAdapter.setIsall(cbAll.isChecked());
                } else {
                    carAdapter.setIsall(false);
                    tvPrice.setText("0.00");
                }
                break;
            case R.id.iv_car_total:
                Log.i(TAG, "onClick: " + bean.getData().toString());
                Log.i(TAG, "onClick: " + tvPrice.getText().toString());
                Intent intent = new Intent(getActivity(), ComfirOrderActivity.class);
                intent.putExtra("total", tvPrice.getText().toString());
                if (bean.getData().size()!=0) {
                    startActivity(intent);
                } else
                    Toast.makeText(getActivity(), "购物车是空的，先添加个商品在下单", Toast.LENGTH_SHORT).show();
                SharedPreferencesUtils.putBean(getActivity(), "carinfo", comfirOrderBean);
                break;
        }
    }

    private void getCar() {
        CommonUtils.showDiaLog(getActivity(), "正在获取数据");
        Map<String, String> map = new HashMap<>();
        map.put("access_token", CommonUtils.getToken(getActivity()));
        HttpUtils.postHttp(map, CommonConstant.cartList, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                CommonUtils.dismissDiaLog();
                if (jsonObject.optInt("code") == 0) {
                    bean = new Gson().fromJson(String.valueOf(jsonObject), CarGoodsBean.class);
                    if (bean != null && bean.getData() != null) {
                        carAdapter.setCarGoodsBean(bean.getData());
                        carAdapter.notifyDataSetChanged();
                    }
                } else if (jsonObject.optInt("code") == 1000005) {
                    Toast.makeText(getActivity(), "" + jsonObject.optString("msg"), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void errorHttp(String msg) {
                CommonUtils.dismissDiaLog();
            }
        });
    }


    private void delCar() {
        Map<String, String> map = new HashMap<>();
        map.put("access_token", CommonUtils.getToken(getActivity()));
        if (carAdapter.getCarId() != null && carAdapter.getCarId().size() > 0) {
            String cart_id = carAdapter.getCarId().toString();
            map.put("cart_id", cart_id.substring(1, cart_id.length() - 1));
        } else {
            Toast.makeText(getActivity(), "请先选择商品", Toast.LENGTH_SHORT).show();
            return;
        }
        CommonUtils.showDiaLog(getActivity(), "正在获取数据");
        HttpUtils.postHttp(map, CommonConstant.removeCart, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                CommonUtils.dismissDiaLog();
                if (jsonObject.optInt("code") == 0) {
                    Toast.makeText(getActivity(), "移除商品成功", Toast.LENGTH_SHORT).show();
                    getCar();
                } else {
                    Toast.makeText(getActivity(), "" + jsonObject.optString("msg"), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void errorHttp(String msg) {
                CommonUtils.dismissDiaLog();
            }
        });
    }

}
